package com.ruoyi.framework.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker // 启用WebSocket消息代理
public class WebSocketConfigBroker implements WebSocketMessageBrokerConfigurer {

    private MyWebSocketHandler myWebSocketHandler;

    public WebSocketConfigBroker(MyWebSocketHandler myWebSocketHandler) {
        this.myWebSocketHandler = myWebSocketHandler;
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 启用简单内存消息代理，用于广播消息
        config.enableSimpleBroker("/topic");
        // 定义客户端发送消息的前缀
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册WebSocket端点，客户端将使用此端点连接
        // withSockJS()用于兼容不支持WebSocket的浏览器
        registry.addEndpoint("/ws")
//                .setHandshakeHandler(myWebSocketHandler)
                .setAllowedOriginPatterns("*");
    }
}
